package com.qi.spzx.manager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qi.spzx.common.exception.GuiguException;
import com.qi.spzx.manager.mapper.SysRoleUserMapper;
import com.qi.spzx.manager.mapper.SysUserMapper;
import com.qi.spzx.manager.service.SysUserService;
import com.qi.spzx.model.dto.system.AssginRoleDto;
import com.qi.spzx.model.dto.system.LoginDto;
import com.qi.spzx.model.dto.system.SysUserDto;
import com.qi.spzx.model.entity.system.SysRole;
import com.qi.spzx.model.entity.system.SysRoleUser;
import com.qi.spzx.model.entity.system.SysUser;
import com.qi.spzx.model.vo.common.ResultCodeEnum;
import com.qi.spzx.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2024/2/21 14:07
 * @Version 1.0.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    /**
     * 用户进行登录
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //  首先获取出来验证码的信息
        String codeKey = loginDto.getCodeKey();
        //  判断验证码的是否为空
        if (ObjectUtil.isNotEmpty(codeKey)) {
            //  根据key从redis中获取value
            String value = (String) redisTemplate.opsForValue().get("user:validate" + codeKey);
            //  将验证码进行比较
            if (StrUtil.isEmpty(value) || !StrUtil.equalsAnyIgnoreCase(loginDto.getCaptcha(), value)) {
                throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
            }
        }
        //  将redis中的验证码进行删除
        redisTemplate.delete("user:validate" + codeKey);
        // 根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null) {
            throw new GuiguException(ResultCodeEnum.USER_NOT_EXICT_ERROR);
        }
        //  判断密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token , JSON.toJSONString(sysUser) , 30 , TimeUnit.MINUTES);
        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        // 返回
        return loginVo;
    }

    /**
     * 根据token查询用户信息
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = (String)redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isNotEmpty(userJson)){
            SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
            return sysUser;
        }else {
            return null;
        }
    }

    /**
     * 退出登录
     * @param token
     */
    @Override
    public void logout(String token) {
        //从redis中进行删除
        redisTemplate.delete("user:login:" + token);
    }

    /**
     * 进行分页查询
     *
     * @param sysUserDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto);
        return PageInfo.of(sysUserList);
    }

    /**
     * 用户进行保存
     *
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        //首先判断用户是否被注册
        String userName = sysUser.getUserName();
        SysUser dbUser = sysUserMapper.selectByUserName(userName);
        if (ObjectUtil.isNotEmpty(dbUser)) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        //进行保存
        sysUserMapper.saveSysUser(sysUser);
    }

    /**
     * 进行用户的修改
     *
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser) ;
    }

    /**
     * 进行用户的删除
     *
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId) ;
    }

    /**
     * 进行用户角色的添加或修改
     *
     * @param assginRoleDto
     */
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        Long userId = assginRoleDto.getUserId();
        //首先根据用户的Id，将关联表中的数据进行全部删除
        sysRoleUserMapper.deleteByUserId(userId);
        //然后根据用户传入的新角色id进行添加
        assginRoleDto.getRoleIdList().forEach( item ->{
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(userId);
            sysRoleUser.setRoleId(item);
            sysRoleUserMapper.add(sysRoleUser);
        });
    }
}
